﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace WeChatParking.Core.Payment.WeixinPay
{
    public class WxpayHelper
    {

        //签名算法
        public static string GetSign(IDictionary<string, string> parameters,string apikey){

            //签名步骤一：按字典key排序参数,不包括sign
            //签名步骤二：在string后加入KEY,并进行MD5算法
            parameters = PayUtil.FilterPara(parameters);
            parameters.Remove("sign");

            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            string stringData = PayUtil.CoverDictionaryToString(sortedParams);
            stringData = stringData + "&key=" + apikey;
            string sign = WeChatParking.Util.Security.GetMd5Hash(stringData).ToUpper();
            return sign;
       }

        //验证签名
        public static bool CheckSign(IDictionary<string, string> parameters,string apikey,string sign)
        {
            string checkSignStr = GetSign(parameters, apikey);
            return checkSignStr.Equals(sign);
        }

        public static bool CheckSign(string xmlStr, string apiKey, string appId, string mchId)
        {
            var xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(xmlStr);

            var dic = new Dictionary<string, string>();
            foreach(System.Xml.XmlNode node in xmlDoc.FirstChild.ChildNodes)
            {
                dic.Add(node.Name, node.InnerText);
            }

            if (dic.ContainsKey("sign") == false)
                return false;

            var sign = dic["sign"];
            dic.Remove("sign");

            if (dic.ContainsKey("appid") == false || dic["appid"] != appId)
                return false;

            if (dic.ContainsKey("mch_id") == false || dic["mch_id"] != mchId)
                return false;

            return CheckSign(dic, apiKey, sign);

        }

       //随机数算法，长度不长于32
       public static string GetNoncestr(int length=32)
       {
           Random rand = new Random();
           string chars = "abcdefghijklmnopqrstuvwxyz0123456789"; 
           StringBuilder noncestr = new StringBuilder() ;
		   for ( int i = 0;i<length;i++ )  {
              noncestr.Append(chars[rand.Next(chars.Length)]);
		   }  
          return noncestr.ToString();
       }

       /// <summary>
       /// 获取时间戳 (10位)
       /// </summary>
       /// <returns></returns>
       public static string GetTimeStamp()
       {
           TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
           return Convert.ToInt64(ts.TotalSeconds).ToString();  
          
       }


       //获取Sha1签名算法
       public static string GetSha1Sign(IDictionary<string, string> parameters)
       {

           //签名步骤一：按字典key排序参数,不包括sign
           //签名步骤二：在string后加入KEY,并进行MD5算法
           parameters = PayUtil.FilterPara(parameters);
           parameters.Remove("sign");

           IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
           string stringData = PayUtil.CoverDictionaryToString(sortedParams);
           string sign = WeChatParking.Util.Security.GetSha1Hash(stringData).ToLower();
           return sign;
       }

      

    }
}
